#include "serialthread.h"


#include <QDateTime>
#include <QDebug>
#include <QSerialPort>
#include "framewindow.h"
#include <QApplication>


SerialThread::SerialThread(FrameWindow *frameWindow)
{
    this->parent = frameWindow;
    isTerminate =true;

}

SerialThread::~SerialThread()
{
    quit();
    wait();
}



int SerialThread::init()
{
    connect(this,&SerialThread::sendData,parent,&FrameWindow::onSendData);
    connect(this,&SerialThread::receiveData,parent,&FrameWindow::showReceiveData);
    connect(this,&SerialThread::sendResult,parent,&FrameWindow::onReceiveResult);
    connect(this,&SerialThread::finished,parent,&FrameWindow::onAutoTestEnd);
    return initialPorts();
}


int SerialThread::initialPorts()
{

    COMMap = new QMap<QString,SerialPortsManager*>;

    foreach ( QString comName,parent->COMLists) {

        SerialPortsManager  *manager = new SerialPortsManager(parent);
        QSerialPort *COM = new QSerialPort();
        manager->serialPort = COM;

        //COM->moveToThread(this);
        COMMap->insert(comName,manager);

    }

    return 0;
}



void SerialThread::run()
{

    init();

    qDebug() << "SerialThread run() started!"<<"currentThreadId: "<<QThread::currentThreadId();
     qDebug() <<"SerialThread: "<<QThread::currentThread();
    if(isTerminate){
        return;
    }

    qDebug() << QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss:zzz")<<"wait() before";

    wait(5000);
    qDebug() <<QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss:zzz")<<"wait() end";


    int loop = 0;
    int cmdIndex =0;

    QString COMName;
    //exec();

    /*
     * 串口循环
     */
    QMap<QString, SerialPortsManager*>::iterator iter1 = COMMap->begin();
    while (iter1 !=COMMap->end())
    {
        loop++;

        COMName = iter1.key();
        qDebug() << "串口名称： "<<COMName;

        iter1.value()->configCOM();
        iter1.value()->openCOM(COMName);


        /*
         * 命令循环
         */

        cmdIndex = 0;
        QLinkedList<ATCommandItem>::iterator iter2;
        for (iter2=parent->commandList.begin();iter2!=parent->commandList.end();iter2++)
        {

            if(!iter2->check){
                cmdIndex++;
                continue;
            }

            QString m;
            m.sprintf(" [%d-%d] ",loop,cmdIndex);

            emit sendData(QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss:zzz ")+COMName+m+iter2->atCommand);
            qDebug() <<QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss:zzz")<<COMName+m<<"发送：";
            qDebug() <<iter2->atCommand;
            // port->write(iter->atCommand.toStdString().c_str());

            iter1.value()->mutex.lock();

            iter1.value()->sendCOM(iter2->atCommand.toLocal8Bit());

            msleep(1000);
            if(isTerminate){
                iter1.value()->mutex.unlock();
                iter1.value()->closeCOM();
                return;
            }
           if (iter1.value()->waitForReceive(5000))
            {

                //从缓冲区中读取数据
                QByteArray buffer = iter1.value()->serialPort->readAll();

                qDebug() <<QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss:zzz")<<COMName<<"接收：";
                qDebug() <<buffer;

                iter1.value()->newReceived=buffer;
                //(COMName,*iter,iter1.value()->newReceived);

                dealData(COMName,*iter2  ,iter1.value()->newReceived);

                emit receiveData(iter1.value()->newReceived);

            }
            iter1.value()->mutex.unlock();

            if(isTerminate){

                iter1.value()->closeCOM();
                quit();
                return;
            }

            cmdIndex++;
        }

        iter1.value()->closeCOM();

        iter1++; //
    }


}



int SerialThread::dealData(QString COM,ATCommandItem  comm, QByteArray rec)
{


    int responseComm = 1;
    int responseStatus =1;
    int responseData =0;
    QString send = comm.atCommand.simplified();

    QString temp;

    QString strRec;
    strRec.prepend(rec);
    strRec = strRec.trimmed();

    QStringList  strs =strRec.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);

    foreach (QString response, strs)
    {

        //if(send==response){
        //    qDebug() <<send<<" == "<<response;
        //     responseComm = 0;
        //}

        // 4GAT命令响应数据示例：
        // "at+cpin?\r\r\n+CPIN: READY\r\nOK\r\n"，回显发送命令
        // “+CPIN: READY\r\nOK\r\n"，没有回显发送命令
        // "at$myccid\r\r\n$MYCCID: \"89860618000015210243\"\r\nOK\r\n"
        // "$MYCCID: \"89860618000015210243\"\r\nOK\r\n"

        // 响应字符是否包含回显发送命令，在AT中可设，所以响应字符不一定回显发送命令
        //使用分号拆分，使用分号前的字符判断响应命令是哪一个发送命令的响应

        QStringList  resCmd = response.split(":");
        if(responseComm !=0 ){
            if(resCmd.length()>0){
                //QString sendUp =  send.toUpper() ; // 转换为大写

                if(send.contains(resCmd.at(0),Qt::CaseInsensitive))//成功返回true 第二个参数表示是否大小写敏感
                {
                    responseComm = 0;
                }
            }
        }





        if(comm.resposeGood ==response){
            responseStatus = 0;
        }

        if(response.contains("+CGREG:")){

            int flag = response.mid(10,1).toInt();
            if(flag == 1|| flag==5){
                responseData =0;
            }
            else {
                responseData =1;
            }
        }

        if(response.contains("+CGATT:")){

            int flag = response.mid(8,1).toInt();
            if(flag == 1){
                responseData =0;
            }
            else {
                responseData =1;
            }
        }

        if(response.contains("$MYSYSINFO:")){

            int flag = response.mid(14,2).toInt();
            if(flag == 1 || flag==2|| flag==3){
                responseData =0;
            }
            else {
                responseData =1;
            }
        }


        temp += response+"  ";

    }

    emit sendResult(COM,temp,responseComm+responseStatus+responseData);

    return 0;
}




